'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        //1.容错处理
        if(username && /^[0-9a-zA-Z]{4,6}$/.test(password)){
            //2.排重
            let target = await service.user.selectUser(username);
            console.log(target);
            if(target.length){
                ctx.body = {
                    code:3,
                    msg:'已注册'
                }
            }else{
                //3.注册
                try{
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(username,hmcPwd);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:0,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username && /^[0-9a-zA-Z]{4,6}$/.test(password)){
            //加密
            let hmcPwd = ctx.helper.hmc(password);
            let target = await service.user.login(username,hmcPwd);
            console.log(target);
            if(target.length){
                //jwt.sign({签入的内容},'私钥',{过期时间})
                let token = jwt.sign({username,role_id:target[0].role_id},'1801b',{expiresIn:60*60*5});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:0,
                msg:'参数有误'
            }
        }
    }

    async list(){
        //role_id
        let {ctx} = this;
        console.log("===list====",ctx.info);
        let {role_id} = ctx.info;
        let list = await this.service.user.list(role_id);
        ctx.body = {
            code:1,
            data:list
        }
    }
}

module.exports = UserController;





